﻿using Peninsula.Web.Infrastructure.Constant;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Peninsula.Web.Models.Sessions;
using Peninsula.Account.Manager;
using Peninsula.Utility.Extensions;

namespace Peninsula.Web.Infrastructure
{
    public class HouseHoldsAuthorizeAttribute: AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpcontext) {

            FormsAuthenticationHelper.RenewCurrentUser();
            if (!base.AuthorizeCore(httpcontext))
            {
                return false;
            }
            else {
                FormsAuthenticationHelper.RenewCurrentUser();
                if (HttpContext.Current.User==null)
                {
                    return false;
                }
                else
                {
                    var HouseholdsSession = HttpContext.Current.Session[SessionConstant.Households_SESSION] as HouseholdsSession;
                    var HouseholdsManger = IOC.Factory.StaticGetObject<HouseholdsManger>();
                    var HouseholdsId = HttpContext.Current.User?.Identity?.Name;
                    if (HouseholdsSession.IsNull())
                    {
                        var households = HouseholdsManger.Get(h => h.Id == HouseholdsId);
                        if (households==null)
                        {
                            return false;
                        }
                        HouseholdsSession = new HouseholdsSession(households);
                        HttpContext.Current.Session[SessionConstant.Households_SESSION] = HouseholdsSession; 
                    }
                      return true;
                        
                }

            }
        }


        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult()
                {
                    Data = new { }//ajax授权失败
                };

            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(RouteConfig.Default,
                    Peninsula.Site.Data.Helper.RouteValuesHelper.From(
                        new {
                            Controller="Account",
                            Action="Login",
                            returnUrl=filterContext.RequestContext.HttpContext.Request.RawUrl
                        }
                        )
                    );
            }
        }
    }
}